let dataObj,spanObj;
window.onload = function () {
    dataObj = document.getElementById("shopData");
    spanObj = document.getElementById("totalSpan");

    var inputArray = dataObj.getElementsByTagName("input");
    for(let i=0;i<inputArray.length;i++){
        var inputObj = inputArray[i];
        if(inputObj.type == 'text'){
            inputObj.onblur = function () {
                changeNum(this);
            }
        }
        else if(inputObj.type == "button"){
            inputObj.onclick = function () {
                removeProduct(this);
            }
        }
    }
    computPrice();
}

//文本框改变数量
function changeNum(txtObj) {
    let num = parseInt(txtObj.value);
    if(isNaN(num)){
        num = 1;
    }
    txtObj.value = num;

    //txtObj.parent得到元素对象的父节点对象
    var price = txtObj.parentElement.previousElementSibling.innerHTML;
    console.log(price+"   "+num);
    txtObj.parentElement.nextElementSibling.innerHTML = price * num;
    computPrice();
}
//移除商品
function removeProduct(buttonObj) {
    // dataObj.removeChild(buttonObj.parentElement.parentElement);
    buttonObj.parentElement.parentElement.remove();
    computPrice();
}

//计算总价
function computPrice() {
    //得到tbody中tr元素数组
    var trArray = dataObj.getElementsByTagName("tr");
    var total = 0;
    for(var i=0;i<trArray.length;i++){
        //得到每一行中td的元素集合
        var tdArray = trArray[i].getElementsByTagName("td");
        total += parseInt(tdArray[3].innerHTML);
    }
    spanObj.innerHTML = total;
}